﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.IO;

namespace Genuilder.Extensibility
{
	[DataContract]
	public class GenItemHistory
	{
		[DataMember]
		public string Name
		{
			get;
			set;
		}
		[DataMember]
		public DateTime LastModified
		{
			get;
			set;
		}
		[DataMember]
		public bool Generated
		{
			get;
			set;
		}

		[DataMember]
		public String Parent
		{
			get;
			set;
		}

		internal static GenItemHistory CreateFrom(ExecutionContext.SourceFile sourceFile)
		{
			return new GenItemHistory()
			{
				Name = sourceFile.Name,
				LastModified = new FileInfo(sourceFile.Name).LastWriteTimeUtc,
				Generated = sourceFile.Generated,
				Parent = sourceFile.Parent.Name
			};
		}

		internal ExecutionContext.SourceFile ToSourceFile()
		{
			return new ExecutionContext.SourceFile(Name)
			{
				Generated = Generated
			};
		}
	}

	[DataContract]
	public class RunHistory
	{
		public RunHistory()
		{
			GenItems = new List<GenItemHistory>();
		}
		[DataMember]
		public List<GenItemHistory> GenItems
		{
			get;
			set;
		}
		public void Save(string path)
		{
			DataContractSerializer serializer = CreateSerializer();
			using(var fs = File.Open(path, FileMode.Create, FileAccess.Write))
			{
				serializer.WriteObject(fs, this);
			}
		}

		private static DataContractSerializer CreateSerializer()
		{
			return new DataContractSerializer(typeof(RunHistory));
		}
		public static RunHistory LoadOrNull(string file)
		{
			if(!File.Exists(file))
				return null;
			DataContractSerializer serializer = CreateSerializer();
			using(var fs = File.Open(file, FileMode.Open, FileAccess.Read))
			{
				return (RunHistory)serializer.ReadObject(fs);
			}
		}

		Dictionary<string, GenItemHistory> _HistoriesByName;
		internal GenItemHistory GetGenItemHistoryByName(string name)
		{
			if(_HistoriesByName == null)
			{
				_HistoriesByName = GenItems.ToDictionary(i => i.Name);
			}
			GenItemHistory result = null;
			_HistoriesByName.TryGetValue(name, out result);
			return result;
		}
	}
}
